package org.jecat.pusher;

import java.io.*;
import java.util.zip.* ;

public class DataCompresser {


	public static void main(String[] args) {
		/*SerializationContext serializationContext = new SerializationContext();
		Amf3Output amfOut = new Amf3Output(serializationContext);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		DataOutputStream dataOutStream = new DataOutputStream(outStream);
		amfOut.setOutputStream(dataOutStream);

		HashMap<String, Object> map = new HashMap<String, Object>();
		Double[] arr = new Double[10000];
		for (int index = 0; index < 10000; index++) {
			arr[index] = Math.random();
		}
		map.put("arr", arr);
		map.put("name", "weni");
		map.put("age", "27");
		try {
			amfOut.writeObject(map);
			dataOutStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] messageBytes = outStream.toByteArray();

		try {
			FileOutputStream os;
			OutputStreamWriter ow;
			BufferedWriter out;
			os = new FileOutputStream("D://test.txt");
			ow = new OutputStreamWriter(os);
			out = new BufferedWriter(ow);
			os.write(messageBytes);
			os.flush();
			os.close();
			messageBytes = compressBytes(messageBytes); // 将数据进行压缩
			System.out.println("OK");
		} catch (Exception e) {
			System.out.println("error  :" + e);
		}*/
	}

	public static byte[] compressBytes(byte input[])
	{
		compresser.reset();
		compresser.setInput(input);
		compresser.finish();
		byte output[] = new byte[0];
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[cachesize];
			int got;
			while (!compresser.finished()) {
				got = compresser.deflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}

	public static byte[] decompressBytes(byte input[])
	{
		byte output[] = new byte[0];
		decompresser.reset();
		decompresser.setInput(input);
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[cachesize];
			int got;
			while (!decompresser.finished()) {
				got = decompresser.inflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}
	

	private static int cachesize = 1024;
	private static Inflater decompresser = new Inflater();
	private static Deflater compresser = new Deflater();

}
